package repository

import (
	"errors"
	"fmt"
	common "git.mashibing.com/msb_47094/shopping-comm"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
	"gouser/domain/model"
	"time"
)

/**
 int32 clientId = 1;
    string phone = 2;
    int32 systemId = 3;
    string verificationCode = 4;
**/
//接口   定义了一个接口类
type IUserRepository interface {
	Login(int32, string, int32, string) (*model.User, error)
	SetUserToken(key string, val []byte, timeTTL time.Duration)
	GetUserToken(key string) string
}

// 初始化的时候方便初始化这个信息，调用
func NewUserRepository(db *gorm.DB, red *redis.Client) IUserRepository {
	return &UserRepository{mysqlDB: db, red: red}
}

// 数据DB  实现类得结构体  实现类得用stryct 去吃
type UserRepository struct {
	mysqlDB *gorm.DB
	red     *redis.Client
}

// 重写接口方法
func (u *UserRepository) Login(clientId int32, phone string, systemId int32, verificationCode string) (user *model.User, err error) {
	user = &model.User{}
	if clientId == 0 && systemId == 0 && verificationCode == "6666" {
		u.mysqlDB.Where("phone = ? ", phone).Find(user)
		//未找到就注册一个
		if user.ID == 0 {
			user.Phone = phone
			u.mysqlDB.Create(&user)
			//u.mysqlDB.Select("Nickname", "Avatar", "Phone", "ClientId").Create(&user)
		}
		return user, nil
		//return user,  u.mysqlDB.Where("phone = ? ", phone).Find(user).Error
	} else {
		return user, errors.New("参数不匹配")
	}
}
func (u *UserRepository) SetUserToken(key string, val []byte, timeTTL time.Duration) {

	intKey := common.ToInt(key)
	binKey := common.ConverToBinary(intKey)
	fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>", binKey)

	common.SetUserToken(u.red, binKey, val, timeTTL)
}

func (u *UserRepository) GetUserToken(key string) string {
	return common.GetUserToken(u.red, key)
}
